package com.spring.bucks.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spring.bucks.model.Coffee;
import com.spring.bucks.model.Order;
import com.spring.bucks.model.OrderCoffee;
import com.spring.bucks.model.OrderState;
import com.spring.bucks.repository.OrderCoffeeMapper;
import com.spring.bucks.repository.OrderMapper;
import com.spring.bucks.vo.CoffeeOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CoffeeOrderService extends ServiceImpl<OrderCoffeeMapper, OrderCoffee> {
    @Autowired
    private OrderCoffeeMapper coffeeOrderMapper;
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 插入订单与订单与咖啡关联表，增加了事物
     * 增删改需要加入事务管理
     * @param customer
     * @param coffees
     * @return
     */
    @Transactional
    public CoffeeOrderVO createOrder(String customer, List<Coffee> coffees) {
        Order order = Order.builder().customer(customer).state(OrderState.INIT.getCode())
                .build();
        orderMapper.insert(order);

        coffees.forEach(co -> {
            OrderCoffee orderCoffee = OrderCoffee.builder()
                    .coffeeOrderId(order.getId())
                    .itemsId(co.getId())
                    .build();
            coffeeOrderMapper.insert(orderCoffee);
        });
        List<OrderCoffee> coffeeList = coffeeOrderMapper.selectList(
                new LambdaQueryWrapper<OrderCoffee>().eq(OrderCoffee::getCoffeeOrderId,order.getId()));
        CoffeeOrderVO coffeeOrderVO = new CoffeeOrderVO();
        BeanUtils.copyProperties(order,coffeeOrderVO);
        coffeeOrderVO.setCoffees(coffees);
        coffeeOrderVO.setOrderCoffees(coffeeList);
        return coffeeOrderVO;
    }

    public boolean updateState(Order order, OrderState state) {
        if (state.getCode().compareTo(order.getState()) > 0) {
            log.warn("Wrong State order: {}, {}", state, order.getState());
            return false;
        }
        order.setState(state.getCode());
        orderMapper.updateById(order);
        log.info("Updated Order: {}", order);
        return true;
    }
}
